﻿using System;
using System.Data;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using ZX.Common;
using ZX.DBModule;
using ZX.BLL.Extend;
using ZX.SYS.Library;
using ZX.SYS.Bussiness.WorkFlow;
using System.Text;
using System.Text.RegularExpressions;
using ZX.Web.UI.Controls;
using ZX.BPM.Library;
using ZX.CRM.Bussiness;
using System.Web.Caching;
namespace ZX.WebApp.Mobi
{
    public partial class AutoFrom : EditUIPage
    {
        #region 属性
        /// <summary>
        /// 流程状态
        /// </summary>
        public string Status
        {
            get;
            set;
        }

        public string OperType
        {
            get;
            set;
        }

        public string FlowCaption
        {
            get;
            set;
        }
        public string DetailsJson
        {
            get;
            set;
        }

        public string DetailsInstance
        {
            get;
            set;
        }

        /// <summary>
        /// 外键表达式
        /// </summary>
        public string FKExpression
        {
            get;
            set;
        }

        /// <summary>
        /// 主键ID值
        /// </summary>
        public object MasterIDValue
        {
            get;
            set;
        }
        /// <summary>
        /// 行为参数
        /// </summary>
        public String Action
        {
            get
            {
                return this.GetStringFromQueryString("action", "");
            }

        }

        public String KeyValue
        {
            set;
            get;
        }
        public string UserName
        {
            get;
            set;
        }

        /// <summary>
        /// 明细页面
        /// </summary>
        public string DetailsPage
        {
            get;
            set;
        }

        public string DeptHtml
        { get; set; }
        BaseEntity MasterEntity = null;
        ZX.WebApp.CrmWorkFlowService.WorkFlowServiceClient client = new CrmWorkFlowService.WorkFlowServiceClient();
        #endregion

        #region
        /// <summary>
        /// 操作实例ID
        /// </summary>
        public string OperatorInsId
        {
            get;
            set;
        }

        /// <summary>
        /// 流程ID
        /// </summary>
        public string WorkFlowId
        {
            get;
            set;
        }
        /// <summary>
        /// 流程务任ID
        /// </summary>
        public string WorkTaskId
        {
            get;
            set;
        }

        /// <summary>
        /// 流程实例ID
        /// </summary>
        public string WorkFlowInsId
        {
            get;
            set;
        }
        /// <summary>
        /// 流程任务实例ID
        /// </summary>
        public string WorkTaskInsId
        {
            get;
            set;
        }
        /// <summary>
        /// 表单类型
        /// </summary>
        public string FormType
        {
            get;
            set;
        }/// <summary>
        /// 表单类型
        /// </summary>
        public string OperStatus
        {
            get;
            set;
        }

        /// <summary>
        /// 是否草稿
        /// </summary>
        public string IsDraft
        {
            get;
            set;
        }


        public string EntityName
        {
            get;
            set;
        }
        public string OperTypeStatus
        {
            get;
            set;
        }

        private string _GetID;
        public string GetID
        {
            get { return _GetID; }
            set
            {
                _GetID = value;
                if (string.IsNullOrEmpty(_GetID))
                {
                    DataAction = "insert";
                }
                else
                {
                    DataAction = "update";
                }

            }
        }
        public string IsIE
        {
            get
            {
                string isIE = "1";
                bool ise = UserPoint();
                isIE = (UserPoint()) ? "0" : "1";
                return isIE;
            }
        }

        /// <summary>
        /// 表名
        /// </summary>
        public string TableName
        {
            get;
            set;
        }


        public string DataAction
        {
            get;
            set;
        }
        public string LoginName
        {
            get;
            set;
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            GetWorkTaskOperType();
            ZX.EHR.Library.DatUser U = HttpContext.Current.Session["User"] as ZX.EHR.Library.DatUser;
            UserName = U.UName.ToString();
            LoginName = U.LoginName;
            InitData();
            InitLoad();
            if (Cache["mobi-deptlist"] == null)//缓存部门列表
            {
                DeptHtml = (new ZX.Web.UI.Controls.UserControl.DeptList()).GetDeptHtml();
                Cache.Insert("mobi-deptlist", DeptHtml, null, DateTime.Now.AddHours(1), Cache.NoSlidingExpiration);
            }
            else
            {
                DeptHtml = (string)Cache["mobi-deptlist"];
            }
        }

        private void InitData()
        {
            if (Request["OperatorInstanceId"] != null)
            {
                OperatorInsId = Request["OperatorInstanceId"].ToString();
                DataTable dt = client.GetOperatorInstanceView(OperatorInsId);
                bool islock = true;

                if (dt != null && dt.Rows.Count > 0)
                {
                    islock = client.IsLock(dt.Rows[0]["WorkTaskInstanceId"].ToString());
                    WorkFlowId = dt.Rows[0]["WorkflowId"].ToString();

                    WorkTaskId = dt.Rows[0]["WorktaskId"].ToString();
                    if (dt.Rows[0]["flStatus"].ToString() == "3")
                    {
                        Status = dt.Rows[0]["flStatus"].ToString();
                    }
                    else if (islock == false)
                    {
                        Status = "2";
                    }
                    else
                    {
                        Status = dt.Rows[0]["Status"].ToString();
                    }
                    WorkFlowInsId = dt.Rows[0]["WorkFlowInstanceId"].ToString();
                    WorkTaskInsId = dt.Rows[0]["WorkTaskInstanceId"].ToString();
                    OperStatus = dt.Rows[0]["OperStatus"].ToString();
                    DataTable cdt = client.GetWorkTaskFormsView(WorkTaskId);
                    DataTable wtdt = client.GetWorkTaskInstanceView(WorkTaskInsId);
                    if (wtdt.Rows.Count > 0)
                    {
                        if (wtdt.Rows[0]["TaskTypeId"].ToString() == "1" && wtdt.Rows[0]["OperStatus"].ToString() == "3" && wtdt.Rows[0]["Status"].ToString() == "2")
                        {
                            IsDraft = "1";
                        }
                        else { IsDraft = "0"; }
                        OperType=wtdt.Rows[0]["OperType"].ToString();
                    }

                    if (cdt != null && cdt.Rows.Count > 0)
                    {
                        FormType = cdt.Rows[0]["FormType"].ToString();

                        if (FormType == "Html")
                        {
                            DataTable tdt = client.GetTableEntity(cdt.Rows[0]["FilePath"].ToString());
                            EntityName = tdt.Rows[0]["MasterTableName"].ToString();
                            string formid = tdt.Rows[0]["FormID"].ToString();
                            GetID = ReturnPayId(WorkFlowInsId, EntityName);

                            if (Status == "3")
                            {
                                DataTable netTaskins = client.GetNetTaskFormID(WorkTaskInsId, WorkTaskId);
                                if (netTaskins.Rows.Count > 0)
                                {
                                    WorkTaskId = netTaskins.Rows[0]["workTaskId"].ToString();
                                    formid = netTaskins.Rows[0]["FilePath"].ToString();
                                }
                            }




                            CreateUI(EntityName, "Select", formid, WorkFlowId, WorkTaskId, "", Status, GetID);

                            //Response.Redirect("MAutoForm.aspx?entity=" + entityName + "&action=Select&formid=" + formid + "&id=" + id + "&workflowid=" + WorkFlowId + "&worktaskid=" + WorkTaskId + "&statues=" + Status + "&WorkFlowInsId=" + WorkFlowInsId);
                        }
                    }
                }
            }

        }


        public void InitLoad()
        {
            //if (Request["OperatorInsId"] != null)
            //{
            //ZX.EHR.Library.DatUser U = HttpContext.Current.Session["User"] as ZX.EHR.Library.DatUser;
            DataTable dts = client.GetAuditMsgTableByFlow(WorkFlowInsId);  //WorkflowInsId
            rptCheckInfo.DataSource = dts;
            rptCheckInfo.DataBind();
            //}
        }
        private void CreateUI(string Entity, string action, string formid, string strWorkFlowId,
            string strWorkTaskId, string FlowCaption, string Status, string id)
        {

            string strEntity = Entity == "" ? "E_Menu" : Entity;
            string strFormID = formid == "" ? Guid.Empty.ToString() : formid;
            FlowCaption = Server.UrlDecode(FlowCaption);

            BaseEntity instance = ZX.Common.Globals.getEntity(strEntity) as BaseEntity;
            MasterEntity = instance;
            BaseBussnies bInstance = new BLL.Extend.BaseBussnies(instance);
            BaseEntity entity = null;
            string strDefaultPropertyValues = "";
            string WorkTaskFormRoles = "";
            string strWorkTaskTitle = "";
            //private void CreateUI()
            //{
            //    string strEntity = this.GetStringFromQueryString("entity", "E_Menu");
            //    string action = this.GetStringFromQueryString("action", "");
            //    string strFormID = this.GetStringFromQueryString("formid", Guid.Empty.ToString());
            //    string strWorkFlowId = this.GetStringFromQueryString("workflowid", "");
            //    string strWorkTaskId = this.GetStringFromQueryString("worktaskid", "");
            //    FlowCaption = Server.UrlDecode(this.GetStringFromQueryString("FlowCaption", ""));
            //    Status = this.GetStringFromQueryString("statues", "");
            //    string id = this.GetStringFromQueryString("id", "");
            //    BaseEntity instance = ZX.Common.Globals.getEntity(strEntity) as BaseEntity;
            //    MasterEntity = instance;
            //    BaseBussnies bInstance = new BLL.Extend.BaseBussnies(instance);
            //    BaseEntity entity = null;
            //    string strDefaultPropertyValues = "";
            //    string WorkTaskFormRoles = "";
            //    string strWorkTaskTitle = "";
            if (instance == null)
            {
                instance = new DataTableBaseEntity();
                ((DataTableBaseEntity)instance).TableName = strEntity;
                string[] strArrary = ((DataTableBaseEntity)instance).GetKey();
                TableName = strEntity;
                if (strArrary != null)
                {
                    ((DataTableBaseEntity)instance).TableKey = strArrary[0];
                    ((DataTableBaseEntity)instance).KeyType = strArrary[1];
                }
                ((DataTableBaseEntity)instance).CreateDT();
                //((DataTableBaseEntity)instance).EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)instance).DRow);

                if (id != "") //有ID表示编辑
                {
                    entity = new DataTableBaseEntity(); //bInstance.GetEntityById(id) as BaseEntity;
                    ((DataTableBaseEntity)entity).TableName = strEntity;
                    ((DataTableBaseEntity)entity).TableKey = ((DataTableBaseEntity)instance).TableKey;
                    ((DataTableBaseEntity)entity).KeyType = ((DataTableBaseEntity)instance).KeyType;
                    ((DataTableBaseEntity)entity).CreateDT(id);
                    ((DataTableBaseEntity)entity).EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                    instance = entity;
                }
                else
                {
                    //初始化ID值
                    //KeyValue = instance.GetTableIdValue();
                    if (KeyValue == Guid.Empty.ToString() || String.IsNullOrEmpty(KeyValue))
                    {
                        ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).TableKey] = Guid.NewGuid();
                    }
                    ((DataTableBaseEntity)instance).EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)instance).DRow);
                    KeyValue = instance.GetTableIdValue();
                    strDefaultPropertyValues = CreateDefaultPropertyValues();
                    strWorkTaskTitle = CreateWorkTaskTitle();
                }

                if (!string.IsNullOrEmpty(strWorkFlowId) && !string.IsNullOrEmpty(strWorkTaskId))
                {
                    WorkTaskFormRoles = CreateWorkTaskFormRoles(strWorkFlowId, strWorkTaskId, strFormID);
                }
            }
            else
            {
                //初始化ID值
                entity = bInstance.GetEntityById(id) as BaseEntity;
                if (entity != null)
                {
                    instance = entity;
                }
            }

            //获取
            if (instance != null)
            {
                object O = instance.GetKeyFieldValue();
                //object O = Globals.GetPropertyValue(instance, instance.GetTableId());
                Guid? _id = ((O) == null) ? null : O as Guid?;
                //初始化ID值
                if (_id == null || _id == Guid.Empty)
                {
                    Globals.SetPropertyValue(instance, instance.GetTableId(), Guid.NewGuid());
                }
            }
            if (!string.IsNullOrEmpty(strWorkFlowId) && !string.IsNullOrEmpty(strWorkTaskId))
            {
                WorkTaskFormRoles = CreateWorkTaskFormRoles(strWorkFlowId, strWorkTaskId, strFormID);
            }

            this.EditTemplate.Text = CreateHtml(instance, entity) + strDefaultPropertyValues + WorkTaskFormRoles + strWorkTaskTitle;
            KeyValue = instance.GetTableIdValue();
            //if (KeyValue == Guid.Empty.ToString())
            //{
            //    ((DataTableBaseEntity)instance).DRow[((DataTableBaseEntity)instance).TableKey] = Guid.NewGuid();
            //}
            //KeyValue =instance["ID"]; //instance.GetTableId();
            //用于定义相关数据绑定信息
            //用于定义相关数据绑定信息
            /////2012.5.8 汪定新修改------------------------------------------------
            string tempCondition = strFormID.Trim() == string.Empty || strFormID.Trim() == Guid.Empty.ToString() ? "FormID='" + strFormID + "' or MasterTableName='" + strEntity + "'" : "FormID='" + strFormID + "'";
            ZX.SYS.Library.SysCustomDefineForm FormEntity = bInstance.GetEntityByCondition<SysCustomDefineForm>(tempCondition);
            string tempCondition2 = strFormID.Trim() == string.Empty || strFormID.Trim() == Guid.Empty.ToString() ? "FormID='" + strFormID + "' or TableName='" + strEntity + "'" : "FormID='" + strFormID + "'";
            IList<ZX.SYS.Library.SysFieldItem> dsList = bInstance.GetEntitys<SysFieldItem>(tempCondition2);
            ///原来的
            //ZX.SYS.Library.SysCustomDefineForm FormEntity = bInstance.GetEntityByCondition<SysCustomDefineForm>("FormID='" + strFormID + "' or MasterTableName='" + strEntity + "'");
            //IList<ZX.SYS.Library.SysFieldItem> dsList = bInstance.GetEntitys<SysFieldItem>("FormID='" + strFormID + "' or TableName='" + strEntity + "'");
            ///------------------------------------------------------------------------------------
            //用于处理
            CreateUIData(dsList);
            if (FormEntity != null)
            {
                DetailsJson = FormEntity.DetailsJson;
                //Dictionary<string, string> _detail = ZX.Common.Globals.JSonToObject<Dictionary<string, string>>(DetailsJson);
                MasterEntity = instance;
                CreateDetailInstance(DetailsJson);
                FormTemplate.Text = ChangFormToMobi(FormEntity.HtmlString);
                this.jSave.Text = ""; //CreateScript(list);
            }
            //this.jInitControl.Text = "";// InitControl(list);
            this.MasterID.Text = SetMasterID();
        }



        #region 样式转换
        private string ChangFormToMobi(string html)
        {
            List<MobiAutoForm> tags = MobiAutoForm.FindTagByAttr(html, "td", "class", "TableData");
            List<MobiAutoForm> cons = MobiAutoForm.FindTagByAttr(html, "td", "class", "TableContent");
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < tags.Count; i++)
            {
                sb.Append("<div><div><label >" + tags[i].InnerHTML + "</label><br/>");
                sb.Append(RegReplace(cons[i].InnerHTML) + "</div></div>");//添加两个DIV，是为了隐藏不显示字段时，主表单还存在
            }

            if (html.Contains("<div id=\"Details\""))
            {//title="人员选择" class="panel"
                // sb.Append();
                int i = html.IndexOf("<div id=\"Details\"");

                string str = html.Substring(i);
                string str1 = str.Insert((str.IndexOf("<div id=\"Details\"") + 5), "title=\"明细信息\" class=\"panel\"  ");

                sb.Append(str1);
                DetailsPage = "<a href=\"javascript:LoadMingxi();\"  class='icon stack'>明细信息</a>";

            }

            return sb.ToString();
        }

        //样式替换
        private string RegReplace(string str)
        {

            Regex reg1 = new Regex("class=\"(.*?)\"");
            if (!reg1.IsMatch(str, 0))
            {
                if (str.Contains(" "))
                {
                    int i = str.IndexOf(" ", 3);
                    string str1 = str.Insert(i, " class='jq-ui-forms' ");
                    str = str1;
                }
            }
            else
            {
                str = reg1.Replace(str, "class='jq-ui-forms'");
            }
            Regex reg2 = new Regex("style=\"(.*?)\"");
            str = reg2.Replace(str, "");

            if (str.Contains("<select"))
            {
                return "<span>" + str + "</span> ";
            }
            else
                return str;
        }

        #endregion


        private void CreateDetailInstance(string DetailsJson)
        {
            //DetailsJson = FormEntity.DetailsJson;
            if (!string.IsNullOrEmpty(DetailsJson))
            {
                IList<SysDetailsItem> list = ZX.Common.Globals.JSonToObject<IList<SysDetailsItem>>(DetailsJson);
                StringBuilder _details = new StringBuilder("");
                foreach (var _detail in list)
                {
                    string table = _detail.DetailsTableName;
                    DataTableBaseEntity entity = new DataTableBaseEntity(); //bInstance.GetEntityById(id) as BaseEntity;
                    ((DataTableBaseEntity)entity).TableName = table;
                    string[] strArrary = ((DataTableBaseEntity)entity).GetKey();
                    if (strArrary != null)
                    {
                        ((DataTableBaseEntity)entity).TableKey = strArrary[0];
                        ((DataTableBaseEntity)entity).KeyType = strArrary[1];
                    }
                    entity.CreateDT();
                    IList<SysTableFKey> fkList = entity.GetFKey();
                    if (fkList != null)
                    {
                        foreach (var e in fkList)
                        {
                            if (e.FKTableName == MasterEntity.GetTableName())
                            {
                                FKExpression = e.FieldName + "='" + KeyValue + "'";
                                entity.SetFieldValue(entity, e.FieldName, KeyValue);
                            }
                        }
                    }
                    else
                    {
                        FKExpression = "1=0";
                    }
                    ((DataTableBaseEntity)entity).EntityJson = ZX.Common.Globals.DataRowToJSON(((DataTableBaseEntity)entity).DRow);
                    _details.Append("var " + table + "=" + ((DataTableBaseEntity)entity).EntityJson + ";").AppendLine();

                }
                DetailsInstance = _details.ToString();
            }
        }


        /// <summary>
        /// 生成对应的下拉数据
        /// </summary>
        /// <param name="fieldList"></param>
        private void CreateUIData(IList<ZX.SYS.Library.SysFieldItem> fieldList)
        {
            this.jInitControl.Text = "";
            if (fieldList == null)
            {
                return;
            }
            StringBuilder strHtml = new StringBuilder("");
            foreach (var e in fieldList)
            {
                IList<Dictionary> list = null;
                if (e.DataSourceType.ToLower() == "json")
                {
                    strHtml.Append("var ds_" + e.FieldName + "=" + e.DataSource + ";\r\n");
                    list = Globals.JSonToObject<IList<Dictionary>>(e.DataSource);
                    string str = "";
                    if (e.ControlsType == "select")
                    {
                        str = "$('#" + e.FieldName + "').comBind(ds_" + e.FieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                    }
                    else
                    {
                        str = "createComboBox('" + e.FieldName + "', { itemSource: ds_" + e.FieldName + ", style: 'dropdown', autoComplete: 'local' });\r\n";
                    }
                    //string str= "$('#"+ e.FieldName+"').comBind(ds_"+e.FieldName+",\"ValueMember\",\"DisplayMember\");";
                    strHtml.Append(str);
                }
                if (e.DataSourceType.ToLower() == "sql")
                {
                    strHtml.Append("var ds_" + e.FieldName + "=");
                    BaseBussnies instance = new BaseBussnies();
                    list = instance.GetEntitysBySqlComm<Dictionary>(e.DataSource.Replace("[B]", "'"));
                    if (list != null)
                    {
                        strHtml.Append(Globals.ObjectToJSON(list) + ";");

                        string str = "";
                        if (e.ControlsType == "select")
                        {
                            str = "$('#" + e.FieldName + "').comBind(ds_" + e.FieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                        }
                        else
                        {
                            str = "createComboBox('" + e.FieldName + "', { itemSource: ds_" + e.FieldName + ", style: 'dropdown', autoComplete: 'local' });\r\n";
                        }
                        //string str = "$('#" + e.FieldName + "').comBind(ds_" + e.FieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                        strHtml.Append(str);
                    }
                    else
                    {
                        strHtml.Append("[];\r\n");
                    }

                }
                if (e.DataSourceType.ToLower() == "dic")
                {
                    strHtml.Append("var ds_" + e.FieldName + "=");
                    BaseBussnies instance = new BaseBussnies();
                    list = instance.GetEntitysBySqlComm<Dictionary>(string.Format("Exec [dbo].[sp_GetDicList] '{0}'", e.DataSource));
                    if (list != null)
                    {
                        strHtml.Append(Globals.ObjectToJSON(list) + ";");
                        string str = "";
                        if (e.ControlsType == "select")
                        {
                            str = "$('#" + e.FieldName + "').comBind(ds_" + e.FieldName + ",\"ValueMember\",\"DisplayMember\");\r\n";
                        }
                        else
                        {
                            str = "createComboBox('" + e.FieldName + "', { itemSource: ds_" + e.FieldName + ", style: 'dropdown', autoComplete: 'local' });\r\n";
                        }
                        strHtml.Append(str);
                    }
                    else
                    {
                        strHtml.Append("[];\r\n");
                    }
                }

                //return string.Format(strSControl, e.FieldName, strHtml.ToString(), width);
            }
            this.jInitControl.Text = strHtml.ToString();
        }

        private string CreateWorkTaskFormRoles(string xWorkFlowId, string xWorkTaskId, string xFormID)
        {
            string _formRoles = "";
            string _DetailsFormRoles = "";
            WorkTaskFormRoles fr = new WorkTaskFormRoles(xWorkFlowId, xWorkTaskId, xFormID);
            Hashtable ht = fr.DetailsPropertyValue;
            foreach (DictionaryEntry de in ht)
            {
                _DetailsFormRoles = "  var DetailsFormRoles=" + de.Value.ToString();
            }

            string _MasterFormRoles = " var MasterFormRoles=" + ZX.Common.Globals.ObjectToJSON(fr.MasterPropertyValue) + ";";
            // string _DetailsFormRoles = "  var DetailsFormRoles=" + 
            return _formRoles = _MasterFormRoles + _DetailsFormRoles;
        }


        private string CreateWorkTaskTitle()
        {
            string workTaskTitle = "";
            string _title = FlowCaption + "-" + this.EmpPropertyValues.Proposer + "-" + "[" + DateTime.Now.ToString("yyyy-MM-dd hh:ss:mm") + "]";
            workTaskTitle = "; var TaskTitle=\"" + _title + "\"";
            return workTaskTitle;
        }


        /// <summary>
        /// 返回业务表单ID   
        /// </summary>
        /// <param name="cpid"></param>
        /// <returns></returns>
        public string ReturnPayId(string cpid, string entity)
        {
            BCrmPayFlow bCrmPayFlow = new BCrmPayFlow();
            string vcp = bCrmPayFlow.GetTableInfoById(cpid == "" ? Guid.NewGuid() : new Guid(cpid), entity);
            if (vcp != null)
            {
                return vcp.ToString();
            }
            return "";
        }


        public void GetWorkTaskOperType()
        {
            if (Request["OperatorInstanceId"] != null)
            {
                DataTable dt = client.GetOperatorInstanceView(Request["OperatorInstanceId"].ToString());
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["OperType"].ToString() == "12")
                    {
                        OperTypeStatus = "1";
                    }

                }
            }

        }

    }
}